package ICM.server;

import java.io.IOException;
import common.*;
import ocsf.server.*;
import ICM.server.ServerUI;
import ICM.server.UserManager;

public class Server extends ObservableServer {
	
	/**
	 * Default listening port
	 */
	public static final int DEFAULT_PORT=5555;
	
	/**
	 * Constructor
	 * @param port
	 */
	public Server(int port) {
		super(port);
	}
	
	/**
	 * Received message handler
	 */
	protected synchronized void handleMessageFromClient(Object message, ConnectionToClient client) {
		setChanged();
		if (message instanceof CommandMessage) {
			notifyObservers(((CommandMessage)message).ToDebugMessage());
			// Handle message
			try {
				client.sendToClient(ParseCommandMessage((CommandMessage)message));
			} catch (IOException e) {
				notifyObservers("Can't send message to client: " + client.getInetAddress().toString());
			}
		}
		else
			notifyObservers(message);
	}
	
	/**
	 * Parse received command message and generate reply message
	 * @param message Received command message and type
	 * @return Reply message
	 */
	private AbstractMessage ParseCommandMessage(CommandMessage txt) {
		if(txt.getCommand().equals(CommandMessage.LOGIN_MESSAGE)) {
			//Check Login and reply
			User u=UserManager.Login(Integer.parseInt((String)txt.getParams()[0]),(String)txt.getParams()[1]);

			return new CommandMessage(CommandMessage.ACKNOWLEDGE_MESSAGE,new Object[] {CommandMessage.LOGIN_MESSAGE,u });
		}
		else if(txt.getCommand().equals(CommandMessage.CREATE_USER)) {
			//Check Login and reply
			int res = UserManager.AddUser(Integer.parseInt((String)txt.getParams()[0]),(String)txt.getParams()[1],(String)txt.getParams()[2],(String)txt.getParams()[3],(String)txt.getParams()[4], (String)txt.getParams()[5]);

			return new CommandMessage(CommandMessage.ACKNOWLEDGE_MESSAGE,new Object[] {CommandMessage.CREATE_USER, res});
		}
		else
			return new TextMessage("Error");
		
	
	}
	
	
	

	/**
	 * Entry point 
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		
		// Create two objects: Server, ServerUI
		Server s = new Server(DEFAULT_PORT);
		ServerUI ui = new ServerUI();
		// Add observer to server
		s.addObserver(ui);
		// Show UI
		ui.setVisible(true);
		
		// Start listening
		try {
			s.listen();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
